<?php

namespace app\api\model;

use think\Model;

/**
 * 房间音频关联模型
 */
class RoomAudioRelation extends Model
{
    protected $name = 'api_room_audio_relations';
    
    // 设置字段信息
    protected $schema = [
        'id'            => 'int',
        'room_id'       => 'int',
        'audio_id'      => 'int',
        'category_type' => 'string',
        'sub_category'  => 'string',
        'sort_order'    => 'int',
        'is_active'     => 'int',
        'create_time'   => 'bigint',
        'update_time'   => 'bigint',
    ];

    // 自动时间戳（毫秒）
    protected $autoWriteTimestamp = false;

    // 状态常量
    const STATUS_ACTIVE = 1;    // 激活
    const STATUS_INACTIVE = 0;  // 未激活

    /**
     * 关联音频模型
     */
    public function audio()
    {
        return $this->belongsTo(Audio::class, 'audio_id', 'id');
    }

    /**
     * 获取房间音频列表（按分类）
     */
    public static function getRoomAudiosByCategory($roomId, $categoryType = null)
    {
        $query = self::alias('r')
            ->leftJoin('api_audios a', 'r.audio_id = a.id')
            ->where('r.room_id', $roomId)
            ->where('r.is_active', self::STATUS_ACTIVE)
            ->where('a.status', Audio::STATUS_NORMAL)
            ->field('r.*, a.name, a.display_name, a.duration, a.file_path, a.format');

        if ($categoryType) {
            $query->where('r.category_type', $categoryType);
        }

        return $query->order('r.category_type, r.sort_order')
            ->select();
    }

    /**
     * 添加音频到房间分类
     */
    public static function addAudioToRoom($roomId, $audioId, $categoryType, $subCategory = null)
    {
        // 检查是否已存在
        $exists = self::where('room_id', $roomId)
            ->where('audio_id', $audioId)
            ->where('category_type', $categoryType)
            ->find();

        if ($exists) {
            return false;
        }

        // 获取当前分类中的最大排序值
        $maxSort = self::where('room_id', $roomId)
            ->where('category_type', $categoryType)
            ->max('sort_order');

        $data = [
            'room_id' => $roomId,
            'audio_id' => $audioId,
            'category_type' => $categoryType,
            'sub_category' => $subCategory,
            'sort_order' => ($maxSort ?? 0) + 1,
            'is_active' => self::STATUS_ACTIVE,
            'create_time' => time() * 1000,
            'update_time' => time() * 1000,
        ];

        return self::create($data);
    }

    /**
     * 更新音频排序
     */
    public static function updateAudioSort($roomId, $categoryType, $sortData)
    {
        foreach ($sortData as $item) {
            $relationId = $item['relation_id'] ?? 0;
            $sortOrder = $item['sort_order'] ?? 0;

            if ($relationId && $sortOrder >= 0) {
                self::where('id', $relationId)
                    ->where('room_id', $roomId)
                    ->where('category_type', $categoryType)
                    ->update([
                        'sort_order' => $sortOrder,
                        'update_time' => time() * 1000
                    ]);
            }
        }

        return true;
    }

    /**
     * 移除音频
     */
    public function remove()
    {
        return $this->delete();
    }

    /**
     * 切换激活状态
     */
    public function toggleActive()
    {
        $newStatus = $this->is_active ? self::STATUS_INACTIVE : self::STATUS_ACTIVE;
        
        return $this->save([
            'is_active' => $newStatus,
            'update_time' => time() * 1000
        ]);
    }

    /**
     * 更新子分类
     */
    public function updateSubCategory($subCategory)
    {
        return $this->save([
            'sub_category' => $subCategory,
            'update_time' => time() * 1000
        ]);
    }

    /**
     * 获取子分类列表
     */
    public static function getSubCategories($categoryType)
    {
        $subCategories = [
            'scene' => ['欢迎语', '感谢语', '互动语', '活动语', '节日语', '提醒语'],
            'background' => ['背景音乐'],
            'other' => []
        ];

        return $subCategories[$categoryType] ?? [];
    }
}
